<?php
namespace cosocket\system\database\pools;

use cosocket\system\database\wrappers\MysqlWrapper;

class MysqlPool
{
    private static $instances = array();
    private static $config = null;

    private static function getMysqlConfig()
    {
        if (self::$config === null) {
            $configFile = PROJ_PATH . "/config/mysql.php";
            if (!file_exists($configFile)) {
                throw new \Exception("MySQL配置文件不存在");
            }
            self::$config = include($configFile);
        }
        return self::$config;
    }

    public static function put($name,$mycli)
    {
        self::$instances[$name]->put($mycli);
    }

    public static function getInstance($name)
    {
        //引入mysql配置 防止重复引入
        $mysqlconfig = self::getMysqlConfig();
        if(empty($mysqlconfig[$name])){
            throw new \Exception(" 找不到mysql数据的配置{$name}");
        }

        $dbconfig = $mysqlconfig[$name];

        $charset="utf8mb4";
        if(!empty($dbconfig['charset'])){
            $charset=$dbconfig['charset'];
        }

        $keyName = $name;
        if(isset(self::$instances[$name])){
            $mycli = self::$instances[$keyName]->get();

            $mycliwrapper =  new MysqlWrapper($name,$mycli);
            $mycliwrapper->query("set names $charset");
            return $mycliwrapper;
        }

        $host = $dbconfig['host'];
        $user = $dbconfig['user'];
        $password = $dbconfig['password'];
        $database = $dbconfig['database'];

        $port=3306;

        if(!empty($dbconfig['port'])){
            $port=$dbconfig['port'];
        }

        $poolsize=64;
        if(!empty($dbconfig['poolsize'])){
            $poolsize=$dbconfig['poolsize'];
        }

        $pool = new \Swoole\Database\MysqliPool((new \Swoole\Database\MysqliConfig)
                ->withHost($host)
                ->withPort($port)
                ->withDbName($database)
                ->withCharset($charset)
                ->withUsername($user)
                ->withPassword($password)
            ,$poolsize);

        self::$instances[$keyName]=$pool;

        $mycli = self::$instances[$keyName]->get();
        $mycliwrapper =  new MysqlWrapper($name,$mycli);
        $mycliwrapper->query("set names $charset");
        return $mycliwrapper;
    }
}
